package com.adaptiveAgingAdmin.exception;

import com.adaptiveAgingAdmin.code.Code;
import com.adaptiveAgingAdmin.code.Result;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 全局异常处理器
 *
 * @author 张涛
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                      HttpServletRequest request) {
        return Result.ERR(null,e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(NotLoginException.class)
    public Result handleNotLoginException(NotLoginException e, HttpServletRequest request) throws IOException {
        return Result.NOT_LOGIN(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e, HttpServletRequest request) throws IOException {
        return Result.ERR(null,e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e, HttpServletRequest request) {
        return Result.EXCEPTION(e.getMessage());
    }

    /**
     * token过期异常
     */
    @ExceptionHandler(TokenExpiredException.class)
    public Result handleTokenExpiredException(TokenExpiredException e, HttpServletRequest request) {
        return new Result(Code.TOKEN_EXPIRE,null,"token过期!");
    }

    /**
     * token非法异常
     */
    @ExceptionHandler(JWTVerificationException.class)
    public Result handleJWTVerificationException(JWTVerificationException e, HttpServletRequest request) {
        return new Result(Code.TOKEN_INVALID,null,"token非法!");
    }

}
